<?php
/**
 * Jobs Model for Jobs World Component
 * 
 * @package    Joomla.Tutorials
 * @subpackage Components
 * @link http://docs.joomla.org/Developing_a_Model-View-Controller_Component_-_Part_2
 * @license    GNU/GPL
 */
 
// No direct access
 
defined( '_JEXEC' ) or die( 'Restricted access' );
 
jimport( 'joomla.application.component.model' );
 
/**
 * Jobs Model
 *
 * @package    Joomla.Tutorials
 * @subpackage Components
 */
class JobsModelRegister extends JModel
{
	/**
	 * Category ata array
	 *
	 * @var array
	 */
	var $_data = null;

	/**
	 * Category total
	 *
	 * @var integer
	 */
	var $_total = null;

	/**
	 * Pagination object
	 *
	 * @var object
	 */
	var $_pagination = null;

	/**
	 * Constructor
	 *
	 * @since 1.5
	 */
	function __construct()
	{
		parent::__construct();

		global $mainframe, $option;

		
	}

	/**
	 * Method to get jobs item data
	 *
	 * @access public
	 * @return array
	 */
	function getData()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->_data))
		{
			$query = $this->_buildQuery();
			$this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));
		}

		return $this->_data;
	}

	/**
	 * Method to get the total number of actor items
	 *
	 * @access public
	 * @return integer
	 */
	function getTotal()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->_total))
		{
			$query = $this->_buildQuery();
			$this->_total = $this->_getListCount($query);
		}

		return $this->_total;
	}

	/**
	 * Method to get a pagination object for the jobs
	 *
	 * @access public
	 * @return integer
	 */
	function getPagination()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->_pagination))
		{
			jimport('joomla.html.pagination');
			$this->_pagination = new JPagination( $this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
		}

		return $this->_pagination;
	}

	function _buildQuery()
	{
		// Get the WHERE and ORDER BY clauses for the query
		$where		= $this->_buildContentWhere();
		$orderby	= $this->_buildContentOrderBy();

		$query = ' SELECT a.*, cc.title AS category, u.name AS editor '
			. ' FROM #__jobs AS a '
			. ' LEFT JOIN #__categories AS cc ON cc.id = a.catid '
			. ' LEFT JOIN #__users AS u ON u.id = a.checked_out '
			. $where
			. $orderby
		;

		return $query;
	}

	function _buildContentOrderBy()
	{
		global $mainframe, $option;

		$filter_order		= $mainframe->getUserStateFromRequest( $option.'filter_order',		'filter_order',		'a.ordering',	'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $option.'filter_order_Dir',	'filter_order_Dir',	'',				'word' );

		// sanitize $filter_order
		if (!in_array($filter_order, array('a.title', 'a.published', 'a.ordering', 'category', 'a.hits', 'a.id'))) {
			$filter_order = 'a.ordering';
		}

		if (!in_array(strtoupper($filter_order_Dir), array('ASC', 'DESC'))) {
			$filter_order_Dir = '';
		}

		if ($filter_order == 'a.ordering'){
			$orderby 	= ' ORDER BY category, a.ordering '.$filter_order_Dir;
		} else {
			$orderby 	= ' ORDER BY '.$filter_order.' '.$filter_order_Dir.' , category, a.ordering ';
		}

		return $orderby;
	}

	function _buildContentWhere()
	{
		global $mainframe, $option;
		$db					=& JFactory::getDBO();
		
		$filter_state		= $mainframe->getUserStateFromRequest( $option.'filter_state',		'filter_state',		'',				'word' );
		$filter_catid		= $mainframe->getUserStateFromRequest( $option.'filter_catid',		'filter_catid',		0,				'int' );
		$filter_order		= $mainframe->getUserStateFromRequest( $option.'filter_order',		'filter_order',		'a.ordering',	'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $option.'filter_order_Dir',	'filter_order_Dir',	'',				'word' );
		$search				= $mainframe->getUserStateFromRequest( $option.'search',			'search',			'',				'string' );
		if (strpos($search, '"') !== false) {
			$search = str_replace(array('=', '<'), '', $search);
		}
		$search = JString::strtolower($search);

		$where = array();

		if ($filter_catid > 0) {
			$where[] = 'a.catid = '.(int) $filter_catid;
		}
		if ($search) {
			$where[] = 'LOWER(a.title) LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
		}
		if ( $filter_state ) {
			if ( $filter_state == 'P' ) {
				$where[] = 'a.published = 1';
			} else if ($filter_state == 'U' ) {
				$where[] = 'a.published = 0';
			}
		}

		$where 		= ( count( $where ) ? ' WHERE '. implode( ' AND ', $where ) : '' );

		return $where;
	}
	function getListImageJobs($id)
    {
		$db =& JFactory::getDBO();
	    $query = 'SELECT * FROM #__jobs_images where jobs_id = '.$id;
	    $db->setQuery( $query );
	    $rows = $db->loadObjectList();
        return $rows;
    }
	function store($post)
	{
	
		$db =& JFactory::getDBO();
		//print_r($post);
		$sex = $post['catid'];
		$title = $post['title'];
		$nickname = $post['nickname'];
		$email = $post['email'];
		$phone = $post['phone'];
		//$birthday = $post['posting_date'];
		$birthday = gmdate('Y-m-d H:i:s',mktime(0, 0, 0, 1, 1, $post['posting_date']));
		
		$city = $post['city'];
		$height = $post['height'];
		$v1 = $post['v1'];
		$v2 = $post['v2'];
		$v3 = $post['v3'];
		$description = $post['description'];
		$date= gmdate('Y-m-d H:i:s');
		$query = "SELECT max(ordering) as 'maxorder' FROM #__jobs";
		$db->setQuery( $query );
		$row=$db->loadObject();
		$ordering = 0;
		if($row) {
			$ordering = $row->maxorder+1;
		}
	    $query = "INSERT INTO `#__jobs` (`catid`, `sid`, `sex`, `title`, `nickname`, `phone`, `city`, `height`, `v1`, `v2`, `v3`, `alias`, `url`, `description`, `date`, `hits`, `published`, `checked_out`, `checked_out_time`, `ordering`, `archived`, `approved`, `region`, `kl`, `contact_person`, `email`, `image`, `shooting_date`, `posting_date`, `close_date`, `params`) VALUES ('".$sex."', '0', '0', '".$title."', '".$nickname."', '".$phone."', '".$city."', '".$height."', '".$v1."', '".$v2."', '".$v3."', '', '', '".$description."', '".$date."', '0', '0', '0', '0000-00-00 00:00:00', '".$ordering."', '0', '1', '0', '', '', '".$email."', '', '0000-00-00 00:00:00', '".$birthday."', '0000-00-00 00:00:00', '')";
		//echo $query;
		//exit();
	    $db->setQuery( $query );
		if($db->query())
		{
			$jobs_id = $db->insertid();
			$max = ini_get('upload_max_filesize');
			$file_type = array("image/png","image/gif","image/jpeg","image/jpg","image/pjpeg");
			$listimage = JRequest::getVar("upload_listimage", null, 'files', 'array'); 
			
			
			
			if(isset($listimage))
			{					
				
				$od = 0;
				for($i=0; $i < sizeof($listimage['error']); $i++)
				{	
					
					if($listimage['error'][$i]==0)
					{		
								
						list($imgfile_name,$error) = $this->fileListUpload($max,'uploads', $file_type , $msg='' ,$listimage['type'][$i],$listimage['name'][$i],$listimage['tmp_name'][$i]);		
						
						if($error) {
							$this->setError($error); 
							
						} else {						
							$query = "INSERT INTO #__jobs_images(jobs_id,image,ordering) values('".$jobs_id."','".$imgfile_name."','" . $od . "')";
							
							$this->_db->setQuery( $query );
							$od++;
								if(!$this->_db->query()) {
									$this->setError($this->_db->getErrorMsg());
									return false;
								}						
						}							
					}				
				}	
				
			}
			
			return true;
		}
	}
	function checkFileUpload($listimage)
	{
		$file_type = array("image/png","image/gif","image/jpeg","image/jpg","image/pjpeg");
		if($listimage)
				{		
					$ok=0;
					
					foreach ($listimage['error'] as $key=>$value)
					{
						if(in_array($listimage['type'][$key],$file_type))
						{
							$ok++;
						}
					}
					
					if($ok > 0)
					{
						return true;
					}
					else
					{
					
						return false;
					}				
				}	
		return false;		
	}
	function saveImage($cid,$image,$od)
	{
		$db =& JFactory::getDBO();
	    $query = "INSERT INTO #__jobs_images(jobs_id,image,ordering) values('".$cid."','".$imgfile_name."','" + $od + "')";
	    $db->setQuery( $query );
		$db->query();
	}
	function fileListUpload($max, $upload_dir='uploads', $file_type, $msg,$file_typeupload,$file_name,$file_tmp_name){
	//Retrieve file details from uploaded file, sent from upload form	
	// Retorna: Array ( [name] => mod_simpleupload_1.2.1.zip [type] => application/zip 
	// [tmp_name] => /tmp/phpo3VG9F [error] => 0 [size] => 4463 ) 
	$filename = "";
	
	if(isset($file_name)){ 
			//Clean up filename to get rid of strange characters like spaces etc
			
			$filename = JFile::makeSafe(time().'_'.$file_name);
	 		
			//if($file['size'] > $max) $msg = JText::_('ONLY_FILES_UNDER').' '.$max;
			//Set up the source and destination of the file
	 
			$src = $file_tmp_name;
			$dest = JPATH_BASE.DS.'administrator'.DS.'components'.DS.'com_jobs' . DS . $upload_dir . DS . $filename;
			//First check if the file has the right extension, we need jpg only
			if ( in_array($file_typeupload,$file_type)) { 			
					
				if ( JFile::upload($src, $dest) ) {	 
					
				   //Redirect to a page of your choice
				//$msg = JText::_('FILE_SAVE_AS').' '.$dest;
			   } else {
				  //Redirect and throw an error message
				$msg = JText::_('ERROR_IN_UPLOAD');
			   }
			} else {
			   //Redirect and notify user file is not right extension
				$msg = JText::_('FILE_TYPE_INVALID');
			}
 		//exit();
		}
		return array($filename,$msg);
	}
	
	
	function fileUpload($max, $upload_dir='uploads', $file_type, $msg,$file){
	//Retrieve file details from uploaded file, sent from upload form	
	// Retorna: Array ( [name] => mod_simpleupload_1.2.1.zip [type] => application/zip 
	// [tmp_name] => /tmp/phpo3VG9F [error] => 0 [size] => 4463 ) 
	$filename = "";
	
	if(isset($file)){ 
			//Clean up filename to get rid of strange characters like spaces etc
			
			$filename = JFile::makeSafe(time().'_'.$file['name']);
	 		
			//if($file['size'] > $max) $msg = JText::_('ONLY_FILES_UNDER').' '.$max;
			//Set up the source and destination of the file
	 
			$src = $file['tmp_name'];
			$dest = JPATH_BASE.DS.'administrator'.DS.'components'.DS.'com_jobs' . DS . $upload_dir . DS . $filename;
			
			
			//First check if the file has the right extension, we need jpg only
			if ( in_array($file['type'],$file_type)) { 			
			//echo $dest;			
				if ( JFile::upload($src, $dest) ) {	 
				   //Redirect to a page of your choice
				//$msg = JText::_('FILE_SAVE_AS').' '.$dest;
			   } else {
				  //Redirect and throw an error message
				$msg = JText::_('ERROR_IN_UPLOAD');
			   }
			} else {
			   //Redirect and notify user file is not right extension
				$msg = JText::_('FILE_TYPE_INVALID');
			}
 		//exit();
		}
		return array($filename,$msg);
	}
}